package cn.com.dhcc.ddi.task.service.notify.impl;

import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.tag.CommonStaticCode;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.app.pub.core.consts.DdiProperties;
import cn.com.dhcc.app.pub.core.tag.staticcode.StaticCode;
import cn.com.dhcc.ddi.task.dao.TableLogDao;
import cn.com.dhcc.ddi.task.dao.TaskDao;
import cn.com.dhcc.ddi.task.dao.TaskExecuteLogDao;
import cn.com.dhcc.ddi.task.service.notify.NotifyInterface;
import cn.com.dhcc.ddi.task.vo.Task;
import cn.com.dhcc.ddi.task.vo.TaskExecuteLog;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @日期：2017/5/10 10:10
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Service(AppIocBean.NOTIFY_LOCALDISK_IMPL)
public class NotifyLocalDiskImpl implements NotifyInterface {
    private static Logger logger = Log.getLogger(Log.LOGTYPE.DDI);
    @Autowired
    private TaskExecuteLogDao taskExecuteLogDao;
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private TableLogDao tableLogDao;
    @Override
    public void reciveNotify(String taskLogId, String status, String msg) throws DaoException {
        //1.交换成功后，将文件服务上的数据文件删除，失败的放入交换失败目录，等待下次再交换
        TaskExecuteLog taskExecuteLog = taskExecuteLogDao.get(taskLogId);
        Task task =  taskDao.get(taskExecuteLog.getTaskId());
        //服务器数据文件存储目录
        String extractPath = DdiProperties.APP_UPLOAD_FILEDATA_PATH + File.separator + TaskExecuteLog.LINK_TYPE.EXTRACT.getEname() + File.separator + task.getId() + File.separator + taskLogId;
        String failPath = DdiProperties.APP_UPLOAD_FILEDATA_PATH + File.separator + "fail" + File.separator + task.getId() + File.separator + taskLogId;
        File failFolder = new File(failPath);
        if (!failFolder.exists()){
            failFolder.mkdir();
        }
        boolean exchangeSuccess = false;
        
        if(CommonStaticCode.SUCCESSFAIL.SUCCESS.getStatus().equals(status)){
            exchangeSuccess = true;
        }
        TaskExecuteLog extractLog = taskExecuteLogDao.getLinkLog(taskLogId, StaticCode.LINK_TYPE.EXTRACT.getCode());

        if(exchangeSuccess){
            if(task.getTaskFreqType().equalsIgnoreCase(StaticCode.TASK_FREQ_TYPE.ONETIME.getCode())){
                task.setStatus(StaticCode.TASK_STATUS.OVER.getCode());
            }else{
                task.setStatus(StaticCode.TASK_STATUS.WAIT.getCode());
            }
            taskExecuteLog.setLogStatus(CommonStaticCode.SUCCESSFAIL.SUCCESS.getStatus());
            taskExecuteLog.setLogMsg("交换成功");
            //交换数据量
            taskExecuteLog.setTotal(extractLog.getTotal());
        }else{
            logger.info("交换失败，下次重发。");
            taskExecuteLog.setLogMsg("交换失败");
            taskExecuteLog.setLogStatus(CommonStaticCode.SUCCESSFAIL.FAIL.getStatus());
            task.setStatus(StaticCode.TASK_STATUS.ERROR.getCode());
        }
        //2.删除映射目录内的原数据文件和映射后数据文件
        List<String> filePathList = JsonUtil.toObjectList(extractLog.getLinkDataFilePath(), String.class);
        try {
            for (String relativePath:filePathList) {
                File file = new File(extractPath + File.separator + relativePath);
                if (!exchangeSuccess){
                    File temp = new File(failPath + File.separator + relativePath);
                    FileUtils.copyFile(file, temp);
                }
                file.delete();
            }
            File extractFolder = new File(extractPath);
            if (extractFolder.exists()){
                extractFolder.delete();
            }
        } catch (IOException e) {
            logger.error("文件复制失败",e);
        }

        //3.更新任务日志状态、任务状态，完成本次数据交换
        taskDao.update(task);
        taskExecuteLog.setTotal(extractLog.getTotal());
        taskExecuteLog.setLinkEndTime(new Date());
        taskExecuteLogDao.update(taskExecuteLog);
    }
}
